using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using ERP.MasterData;
using ERP.MasterData.Dtos;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Linq;

namespace ERP.Web.Controllers
{
    public class WorkshopController : Controller
    {
        private readonly IWorkshopService _workshopService;
        private readonly ILogger<WorkshopController> _logger;

        public WorkshopController(
            IWorkshopService workshopService,
            ILogger<WorkshopController> logger)
        {
            _workshopService = workshopService;
            _logger = logger;
        }

        /// <summary>
        /// 车间设置页面
        /// </summary>
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 测试车间服务
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> Test()
        {
            try
            {
                _logger.LogInformation("测试车间服务");
                
                var input = new GetWorkshopInputDto
                {
                    MaxResultCount = 10,
                    SkipCount = 0
                };
                
                var result = await _workshopService.GetListAsync(input);
                
                return Json(new
                {
                    success = true,
                    message = "测试成功",
                    totalCount = result.TotalCount,
                    dataCount = result.Items?.Count ?? 0,
                    data = result.Items
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "测试车间服务失败");
                return Json(new
                {
                    success = false,
                    message = ex.Message,
                    innerException = ex.InnerException?.Message
                });
            }
        }

        /// <summary>
        /// 获取车间列表数据
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetList(
            [FromQuery] string? workshopCode = null,
            [FromQuery] string? workshopName = null,
            [FromQuery] bool? isActive = null,
            [FromQuery] string? keyword = null,
            [FromQuery] int page = 1,
            [FromQuery] int limit = 10,
            [FromQuery] string? sorting = null)
        {
            try
            {
                _logger.LogInformation("获取车间列表，参数: workshopCode={WorkshopCode}, workshopName={WorkshopName}, isActive={IsActive}, keyword={Keyword}, page={Page}, limit={Limit}", 
                    workshopCode, workshopName, isActive, keyword, page, limit);
                
                // 计算跳过的记录数
                int skipCount = (page - 1) * limit;
                
                var input = new GetWorkshopInputDto
                {
                    WorkshopCode = workshopCode ?? string.Empty,
                    WorkshopName = workshopName ?? string.Empty,
                    IsActive = isActive,
                    Keyword = keyword ?? string.Empty,
                    MaxResultCount = limit,
                    SkipCount = skipCount,
                    Sorting = sorting ?? string.Empty
                };
                
                var result = await _workshopService.GetListAsync(input);
                
                return Json(new
                {
                    code = 0,
                    msg = "",
                    count = result.TotalCount,
                    data = result.Items
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取车间列表失败");
                return Json(new
                {
                    code = 500,
                    msg = ex.Message,
                    count = 0,
                    data = new List<WorkshopDto>()
                });
            }
        }

        /// <summary>
        /// 获取车间详情
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetById(int id)
        {
            try
            {
                _logger.LogInformation("获取车间详情，ID: {Id}", id);
                var result = await _workshopService.GetAsync(id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取车间详情失败，ID: {Id}", id);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 生成车间编码
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GenerateCode()
        {
            try
            {
                var code = await _workshopService.GenerateWorkshopCodeAsync();
                _logger.LogInformation("生成车间编码: {Code}", code);
                return Json(new { success = true, code = code });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成车间编码失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 创建车间
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Create([FromBody] CreateWorkshopDto input)
        {
            _logger.LogInformation("创建车间，参数: {@Input}", input);
            
            if (!ModelState.IsValid)
            {
                var errors = string.Join("; ", ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage));
                _logger.LogWarning("创建车间参数验证失败: {Errors}", errors);
                return Json(new { success = false, message = errors });
            }

            try
            {
                var result = await _workshopService.CreateAsync(input);
                _logger.LogInformation("创建车间成功，ID: {Id}", result.Id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建车间失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 更新车间
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Update([FromBody] UpdateWorkshopDto input)
        {
            _logger.LogInformation("更新车间，参数: {@Input}", input);
            
            if (!ModelState.IsValid)
            {
                var errors = string.Join("; ", ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage));
                _logger.LogWarning("更新车间参数验证失败: {Errors}", errors);
                return Json(new { success = false, message = errors });
            }

            try
            {
                var id = input.Id;
                var result = await _workshopService.UpdateAsync(id, input);
                _logger.LogInformation("更新车间成功，ID: {Id}", id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新车间失败，ID: {Id}", input.Id);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 删除车间（支持单删和批删）
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Delete([FromBody] List<int> ids)
        {
            _logger.LogInformation("删除车间，IDs: {@Ids}", ids);
            
            if (ids == null || !ids.Any())
            {
                return Json(new { success = false, message = "请选择要删除的车间" });
            }

            try
            {
                await _workshopService.DeleteAsync(ids);
                _logger.LogInformation("删除车间成功，数量: {Count}", ids.Count);
                return Json(new { success = true, message = $"成功删除 {ids.Count} 个车间" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除车间失败");
                return Json(new { success = false, message = ex.Message });
            }
        }
    }
} 